var schedule = require("node-schedule");
const moment = require("moment");
var rule = new schedule.RecurrenceRule();
rule.second = 23;
// rule.minute = 23;
const CompayPayment = require('../tools/companyPayment');
const compayPayment = new CompayPayment();
const newUserActiveService = require('../service/newUserActive');
const signService = require('../service/sign');
schedule.scheduleJob(rule, async () => {
    let nowDateStr = moment().format('YYYYMMDDHHmmss');
    const activeConfig = await newUserActiveService.getH5activeConfig(1);
    console.log('新用户分享文章活动配置信息,', activeConfig)
    let activeOk = activeConfig.startTime <= nowDateStr && activeConfig.endTime > nowDateStr;
    if (activeOk) {
        let now = moment().format('YYYY/MM/DD HH:mm:ss');
        let dataStr = moment().format('YYYYMMDD');
        // if (nowHour > 9 && nowHour < 16) {
        /**
         * https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_4&index=3
         * 因为微信限制频率
         * 1.发送频率限制------默认30/秒
         * 2.发送个数上限------默认30/秒
         */
        const userArray = await newUserActiveService.queryDateStrRedEnvByStatusNewUserActive(0, dataStr);
        console.log('新用户没有发放红包的人员', dataStr, userArray);
        let successSendEnvLopOpenIds = [];
        if (userArray.length) {
            for (let user of userArray) {
                const isFocusWxPub = await signService.isFocusWxPub(user.unionId, user.openId);
                if (isFocusWxPub && isFocusWxPub.status == 1) {
                    //发红包
                    const {
                        flag,
                        respData
                    } = await compayPayment.wxcompay({
                        amount: user.amount || 0,
                        openid: user.openId
                    });
                    if (flag) {
                        successSendEnvLopOpenIds.push(user.openId);
                    }
                    console.log('发放新用户红包结果', now, user.openId, flag, respData)

                }
            }
            if (successSendEnvLopOpenIds.length) {
                //批量更新发放红包结果
                let batchUpdateRedEnvopStatusResult = await signService.batchUpdateRedEnvopStatus(1, successSendEnvLopOpenIds, dataStr, 'newUserActive');
                console.log('批量更新新用户发放红包结果', successSendEnvLopOpenIds.join(','), batchUpdateRedEnvopStatusResult);
            }
        }
    }
});